var json="";
$(document).on('click','#arborShow',function(){
	var i=1;
	$('dl').children().each(function(){
		if(i%2==1){
			json=json+"\""+$(this).text()+"\":";
			i++;
		}else{
			json=json+"\""+$(this).text()+"\",";
			i++;
		}
	});
	json = json.substring(0,json.length-1);
	json = "{\"标题\":\""+title+"\","+json+"}";
	
	json = eval('(' + json + ')');
	drawGraph(json);
});	


//
//main.js
//
//A project template for using arbor.js
//

function drawGraph(json){

var Renderer = function(canvas){
    var canvas = document.getElementById('viewport');
var ctx = canvas.getContext("2d");
var particleSystem;

var that = {
  init:function(system){
    //
    // the particle system will call the init function once, right before the
    // first frame is to be drawn. it's a good place to set up the canvas and
    // to pass the canvas size to the particle system
    //
    // save a reference to the particle system for use in the .redraw() loop
    particleSystem = system

    // inform the system of the screen dimensions so it can map coords for us.
    // if the canvas is ever resized, screenSize should be called again with
    // the new dimensions
    particleSystem.screenSize(canvas.width, canvas.height) ;
    particleSystem.screenPadding(100); // leave an extra 80px of whitespace per side
    
    // set up some event handlers to allow for node-dragging
    that.initMouseHandling();
  },
  
  redraw:function(){
    // 
    // redraw will be called repeatedly during the run whenever the node positions
    // change. the new positions for the nodes can be accessed by looking at the
    // .p attribute of a given node. however the p.x & p.y values are in the coordinates
    // of the particle system rather than the screen. you can either map them to
    // the screen yourself, or use the convenience iterators .eachNode (and .eachEdge)
    // which allow you to step through the actual node objects but also pass an
    // x,y point in the screen's coordinate system
    // 
    ctx.fillStyle = "#dde0e8";
    ctx.fillRect(0,0, canvas.width, canvas.height);
    particleSystem.eachEdge(function(edge, pt1, pt2){
      // edge: {source:Node, target:Node, length:#, data:{}}
      // pt1:  {x:#, y:#}  source position in screen coords
      // pt2:  {x:#, y:#}  target position in screen coords

      // draw a line from pt1 to pt2
      ctx.strokeStyle = "rgba(0,0,0, .333)";
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.moveTo(pt1.x, pt1.y);
      ctx.lineTo(pt2.x, pt2.y);
      ctx.stroke();
    });

    particleSystem.eachNode(function(node, pt){
      // node: {mass:#, p:{x,y}, name:"", data:{}}
      // pt:   {x:#, y:#}  node position in screen coords

      // draw a rectangle centered at pt
      var w = 10;
    //  ctx.fillStyle = (node.data.alone) ? "orange" : "red"
    //   ctx.oval(pt.x-w/2, pt.y-w/2, 10,10)
       
       
    //   ctx.stroke()
      ctx.beginPath();
      ctx.arc(pt.x-w/2, pt.y-w/2,20,0,360,false);
      ctx.fillStyle=(node.data.alone) ? "orange" : node.data.color;//填充颜色,默认是黑色
      ctx.fill();//画实心圆
      ctx.closePath();

      ctx.font="14px Arial";
      ctx.fillStyle = "#000";
      
      if(node.name=="详情"&&node.data.label.length>20){
    	var detail = node.data.label;
    	detail = detail.substring(0,20)+"...";
    		  ctx.fillText(detail,pt.x-5,pt.y);
    	    
      }else{
    	   ctx.fillText(node.data.label,pt.x-5,pt.y);
      }
   

    })    	

    particleSystem.eachEdge(function(edge, pt1,pt2){
      // node: {mass:#, p:{x,y}, name:"", data:{}}
      // pt:   {x:#, y:#}  node position in screen coords

      // draw a rectangle centered at pt
      if(edge.data.label!="标题"){
        ctx.font="16px Arial";
        ctx.fillText(edge.data.label,(pt1.x+pt2.x)/2,(pt1.y+pt2.y)/2);

      }
   
    })    		
  },
  
  initMouseHandling:function(){
    // no-nonsense drag and drop (thanks springy.js)
    var dragged = null;
        var _mouseP = null;
var selected = null;

var nearest = null;
var oldmass = 1;
    // set up a handler object that will initially listen for mousedowns then
    // for moves and mouseups while dragging
    var handler = {
      clicked:function(e){
        // var pos = $(canvas).offset();
        // _mouseP = arbor.Point(e.pageX-pos.left, e.pageY-pos.top)
        // dragged = particleSystem.nearest(_mouseP);

        // if (dragged && dragged.node !== null){
        //   // while we're dragging, don't let physics move the node
        //   dragged.node.fixed = true
        // }
      var tr="<tr ><th>属性</th><th>值</th></tr>";
      var pos = $(canvas).offset();
      _mouseP = arbor.Point(e.pageX - pos.left, e.pageY - pos.top);
      nearest = particleSystem.nearest(_mouseP);
      
      if (nearest!=undefined && nearest!=null && nearest.node !== null){
        dragged = selected = (nearest.distance < 50) ? nearest : null;
        if(selected){
          selected.node.fixed = true;

      //更新表格
      $('#tbody').empty() ;
      tr += "<tr><td>"+selected.node.name+"</td><td>"+selected.node.data.label+"</td></tr>";
        $('#tbody').append(tr);
     //  $('.a').fadeIn();
      // $('.a').left = selected.node.p.x+"px";
      //  $('.a').top = selected.node.p.y+"px";
  //  var offset = $('.a').offset(); //获取到这个元素的位置
// $('.a').offset({ top: e.pageY, left: e.pageX});
    }
    else{
    //  $('.a').fadeOut();
    $('#tbody').empty() ;
    tr="<tr ><th>属性</th><th>值</th></tr>";
     for(var i in json){
  //初始化表格
       tr += "<tr><td>"+i+"</td><td>"+json[i]+"</td></tr>";
    }
      $('#tbody').append(tr);
    }
  }
  
        $(canvas).bind('mousemove', handler.dragged)
        $(window).bind('mouseup', handler.dropped)

        return false
      },
      dragged:function(e){
        var pos = $(canvas).offset();
        var s = arbor.Point(e.pageX-pos.left, e.pageY-pos.top)

        if (dragged && dragged.node !== null){
          var p = particleSystem.fromScreen(s);
          $('.a').offset({ top: e.pageY, left: e.pageX});
          dragged.node.p = p
        }

        return false
      },

      dropped:function(e){
        if (dragged===null || dragged.node===undefined) return
        if (dragged.node !== null){
          dragged.node.fixed = false;
        //   $('.a').offset({ top: e.pageY, left: e.pageX});
        } 
        dragged.node.tempMass = 1000;
        dragged = null
        $(canvas).unbind('mousemove', handler.dragged)
        $(window).unbind('mouseup', handler.dropped)
        _mouseP = null
        return false
      },
       
       
    }
    
    // start listening
    $(canvas).mousedown(handler.clicked);

  },
 
  
}
return that
}    

$(document).ready(function(){
var tr="<tr ><th>属性</th><th>值</th></tr>";
var sys = arbor.ParticleSystem(1000, 600, 0.5) // create the system with sensible repulsion/stiffness/friction
sys.parameters({gravity:true}) // use center-gravity to make the graph settle nicely (ymmv)
sys.renderer = Renderer("#viewport") // our newly created renderer will have its .init() method called shortly by sys...



sys.addNode('标题',{label:json['标题'],color:'#ff9800'});
for(var i in json){
  if(i!='标题'){
     sys.addNode(i,{label:json[i],color:'#8bc34a'});
     sys.addEdge('标题',i,{label:i});
  }
  //初始化表格
  tr += "<tr><td>"+i+"</td><td>"+json[i]+"</td></tr>";
}
$('#tbody').append(tr);

// or, equivalently:
//
// sys.graft({
//   nodes:{
//     f:{alone:true, mass:.25}
//   }, 
//   edges:{
//     a:{ b:{},
//         c:{},
//         d:{},
//         e:{}
//     }
//   }
// })

})

}